package com.ray.woodencreate.result;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.Map;
import java.util.Properties;

/**
 * @author bo shen
 * @Description: 系统错误信息
 * @Class: MsgCodeUtil
 * @Package com.toptoday.woodencreate.result
 * @date 2018/10/9 15:14
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
@Component
public class MsgCodeUtil implements CommandLineRunner {

    private final  static String  MSG_CODE_FILE_PATH ="msgCode.properties";

    private final  static String  APP_MSG_CODE_FILE_PATH ="appMsgCode.properties";

    private static Map<String,String> msgCodeMap = Maps.newHashMap();

    @Override
    public void run(String... args) throws Exception {
        if(log.isDebugEnabled()){
            log.debug("MsgCodeUtil load file start.");
        }
        loadMsgCode();
        if(log.isDebugEnabled()){
            log.debug("MsgCodeUtil load file end.");
        }
    }

    /**
     * 加载消息编码数据
     */
    private void loadMsgCode() {
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            Properties properties =  PropertiesLoaderUtils.loadAllProperties(MSG_CODE_FILE_PATH);
            loadAllPropertis(properties);
            Properties appProperties =  PropertiesLoaderUtils.loadAllProperties(APP_MSG_CODE_FILE_PATH);
            loadAllPropertis(appProperties);
            stopWatch.stop();
            log.info("加载消息信息耗时:{}",stopWatch.getTotalTimeMillis());
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 解析文件数据
     * @param properties
     */
    private void loadAllPropertis(Properties properties) {
        String keyStr = null;
        for(Object key : properties.keySet()){
            keyStr = key.toString();
            try {
                msgCodeMap.put(keyStr,new String(properties.getProperty(keyStr).getBytes("UTF-8"),"UTF-8"));
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

    /**
     * 获取消息对应的描述信息
     * @param key
     * @return 消息对应的具体描述信息
     */
    public static  String getMsgCodeMessage(String key){
        String message = msgCodeMap.get(key);
        if(!StrUtil.isBlank(message)){
            return message;
        }
        return  key;
    }

    /**
     * 判断是否存在错误消息key
     * @param errorCode
     * @return
     */
    public static boolean exist(String errorCode) {
        return msgCodeMap.get(errorCode) != null;
    }
    /**
     * 判断是否存在错误消息key
     * @param errorCode
     * @return
     */
    public static boolean notExist(String errorCode) {
        return !exist(errorCode);
    }
}


